/*
 * =====================================================================================
 *
 *       Filename:  serial.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2010-1-14 14:27:03
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  张景福  (jionfull), jionfull@163.com
 *        Company:  
 *
 * =====================================================================================
 */

#include	<reg51.h>
#include "reg51bit.h"
#include "..\..\include\typedef.h"
#include "..\..\include\bitopt.h"
#include "..\..\include\fifo.h"
#include "config.h"
#include "..\..\include\interrupt.h"
/* 
 * ===  FUNCTION  ======================================================================
 *         Name:  InitSerial
 *  Description:  
 * =====================================================================================
 */
#ifdef  TX_FIFO_ON
//#ifdef __C51__
//uint8 data serialTxBuf[TX_FIFO_MAX];
// Fifo data serialTxFifo;
//#else
 uint8 idata serialTxBuf[TX_FIFO_MAX];
 Fifo  serialTxFifo;
//#endif
uint8 txState;
#define TXBUSY 0x01
#endif     /* -----  not TX_FIFO_ON  ----- */

#ifdef  RX_FIFO_ON
static uint8 serialRxBuf[TX_FIFO_MAX];
static Fifo serialRxFifo;
#endif     /* -----  not RX_FIFO_ON  ----- */

void  Serial_Init()
{
#ifdef TX_FIFO_ON
	Fifo_Init(&serialTxFifo,serialTxBuf,TX_FIFO_MAX);
#endif
#ifdef RX_FIFO_ON
	Fifo_Init(&serialRxFifo,serialRxBuf,RX_FIFO_MAX);
#endif

#ifdef  SERMOD_SPI
	
I	SCON = SM_MODE0	;
	
#endif     /* -----  not SERMOD_SPI  ----- */
#ifdef SERMOD_UART8
	SCON = SM_UART_BIT8+BIT_REN;
   
	SETT1MOD(TMOD_MODE2);
	 SETBIT(TCON,BIT_TR1);
	//TH1 =0xfd;
	TH1=256-(FOSC/(384*BAUD));
	TR1=1;
#endif
	
	IE |= BIT_INT_ENSER;
}


void Serial_Send(uint8 sendChar) reentrant
{
	if(CHKBIT(txState,TXBUSY))
	{
		
		if(!Fifo_CheckFull(&serialTxFifo))
		{
			Fifo_WriteFifo(&serialTxFifo,sendChar);
		}
	}
	else
	{
		SBUF=sendChar;
		
		SETBIT(txState,TXBUSY);
		txState=TXBUSY;
	}
}

void Serial_SendArr(uint8 buf[],uint8 len) reentrant 
{
	uint8 i;
	for(i=0;i<len;i++)
	{
		Serial_Send(buf[i]);
	}
}
uint8 Serial_Recive(unsigned char *readChar)               /* 未完成 */
{
	return Fifo_ReadFifo(&serialRxFifo,readChar);

}

uint8 Serial_ChkNoEmpty()
{
		return Fifo_CheckNoEmpty(&serialRxFifo);

}

/* 
 * ===  FUNCTION  ======================================================================
 *         Name:  SerialInterrupt
 *  Description:  
 * =====================================================================================
 */
void serialInterrupt ( ) interrupt 4
{
	uint8 data temp;
	if(TI)
	{
		TI=0;
#ifdef TX_FIFO_ON 
		if(Fifo_CheckNoEmpty(&serialTxFifo))
		{
			Fifo_ReadFifo(&serialTxFifo,&temp);
			SBUF=temp;
		}
		else
		{
			CLRBIT(txState,TXBUSY);
			App_SendEmptyOpt();
		}
#else
		App_SendEmptyOpt();
#endif
	}
	if(RI)
	{
	 	RI=0;                           /* 未写完 */
		temp=SBUF;
		Fifo_WriteFifo(&serialRxFifo,temp);
	}
	return;
}		/* -----  end of function   ----- */
